from datetime import datetime

from django.db.models import Q
from django_redis import get_redis_connection
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.backends import ModelBackend, UserModel
def generate_jwt_token(user):
    token = str(RefreshToken.for_user(user).access_token)
    return {'token': token}


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # 添加额外的用户信息到 注意这个是SIMPLE_JWT 中
        if hasattr(user, 'avatar'):
            token['avatar'] = user.avatar.url if user.avatar else ''

        if hasattr(user, 'nickname'):
            token['nickname'] = user.nickname

        if hasattr(user, "signature"):
            token['signature'] = user.signature
        if hasattr(user, "gender"):
            token['gender'] = user.gender

        return token

    def validate(self, attrs):
        data = super().validate(attrs)
        return data


class CustomAuthBackend(ModelBackend):
    """
    自定义用户认证类[实现多条件登录]
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        多条件认证方法
        :param request: 本次客户端的http请求对象
        :param username:  本次客户端提交的用户信息，可以是user，也可以mobile或其他唯一字段
        :param password: 本次客户端提交的用户密码
        :param kwargs: 额外参数
        :return:
        """
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)

        if username is None or password is None:
            return

        # 根据用户名信息useranme获取账户信息
        user = UserModel.objects.filter(Q(username=username) | Q(mobile=username), disable_time__gte=datetime.now()).first()
        if user and user.check_password(password) and self.user_can_authenticate(user):
            return user


